/**
 * 请求验证中间件
 */

import type { Context } from 'elysia';
import { Validator, ValidationSchema, CommonValidationRules } from '../utils/validation';
import { ApiError } from '../utils/response';

/**
 * 创建验证中间件
 */
export function createValidationMiddleware(schema: ValidationSchema) {
  return ({ body, set }: Context) => {
    try {
      Validator.validateAndThrow(body, schema);
    } catch (error) {
      if (error instanceof ApiError) {
        set.status = error.statusCode;
        throw error;
      }
      throw ApiError.validation('请求参数验证失败');
    }
  };
}

/**
 * 验证查询参数
 */
export function validateQuery(schema: ValidationSchema) {
  return ({ query, set }: Context) => {
    try {
      Validator.validateAndThrow(query, schema);
    } catch (error) {
      if (error instanceof ApiError) {
        set.status = error.statusCode;
        throw error;
      }
      throw ApiError.validation('查询参数验证失败');
    }
  };
}

/**
 * 验证路径参数
 */
export function validateParams(schema: ValidationSchema) {
  return ({ params, set }: Context) => {
    try {
      Validator.validateAndThrow(params, schema);
    } catch (error) {
      if (error instanceof ApiError) {
        set.status = error.statusCode;
        throw error;
      }
      throw ApiError.validation('路径参数验证失败');
    }
  };
}

/**
 * 常用验证中间件
 */
export const ValidationMiddleware = {
  // 用户相关验证
  validateUserCreate: createValidationMiddleware({
    username: CommonValidationRules.username,
    password: CommonValidationRules.password,
    email: CommonValidationRules.email,
    role: { ...CommonValidationRules.role, required: false }
  }),

  validateUserUpdate: createValidationMiddleware({
    username: { ...CommonValidationRules.username, required: false },
    password: { ...CommonValidationRules.password, required: false },
    email: { ...CommonValidationRules.email, required: false },
    role: { ...CommonValidationRules.role, required: false },
    status: { ...CommonValidationRules.status, required: false }
  }),

  validateUserLogin: createValidationMiddleware({
    username: CommonValidationRules.username,
    password: CommonValidationRules.password
  }),

  validateUserRegister: createValidationMiddleware({
    username: CommonValidationRules.username,
    password: CommonValidationRules.password,
    email: CommonValidationRules.email
  }),

  validateChangePassword: createValidationMiddleware({
    oldPassword: CommonValidationRules.password,
    newPassword: CommonValidationRules.password
  }),

  // 产品相关验证
  validateProductCreate: createValidationMiddleware({
    title: CommonValidationRules.productTitle,
    content: { ...CommonValidationRules.productContent, required: false },
    priceRange: {
      type: 'string' as const,
      required: false,
      maxLength: 50,
      message: '价格范围不能超过50字符'
    },
    craftType: {
      type: 'string' as const,
      required: false,
      maxLength: 50,
      message: '工艺类型不能超过50字符'
    },
    images: {
      type: 'array' as const,
      required: false
    },
    features: {
      type: 'array' as const,
      required: false
    },
    tags: {
      type: 'array' as const,
      required: false
    }
  }),

  validateProductUpdate: createValidationMiddleware({
    title: { ...CommonValidationRules.productTitle, required: false },
    content: { ...CommonValidationRules.productContent, required: false },
    priceRange: {
      type: 'string' as const,
      required: false,
      maxLength: 50,
      message: '价格范围不能超过50字符'
    },
    craftType: {
      type: 'string' as const,
      required: false,
      maxLength: 50,
      message: '工艺类型不能超过50字符'
    },
    images: {
      type: 'array' as const,
      required: false
    },
    features: {
      type: 'array' as const,
      required: false
    },
    tags: {
      type: 'array' as const,
      required: false
    },
    status: { ...CommonValidationRules.status, required: false },
    sort: { ...CommonValidationRules.sort, required: false }
  }),

  // 案例相关验证
  validateCaseCreate: createValidationMiddleware({
    title: CommonValidationRules.caseTitle,
    description: { ...CommonValidationRules.caseDescription, required: false },
    categoryId: CommonValidationRules.id,
    industry: {
      type: 'string' as const,
      required: false,
      maxLength: 50,
      message: '行业不能超过50字符'
    },
    client: {
      type: 'string' as const,
      required: false,
      maxLength: 100,
      message: '客户名称不能超过100字符'
    },
    projectDate: {
      type: 'string' as const,
      required: false,
      pattern: /^\d{4}-\d{2}-\d{2}$/,
      message: '项目日期格式应为YYYY-MM-DD'
    },
    images: {
      type: 'array' as const,
      required: false
    },
    services: {
      type: 'array' as const,
      required: false
    },
    tags: {
      type: 'array' as const,
      required: false
    }
  }),

  validateCaseUpdate: createValidationMiddleware({
    title: { ...CommonValidationRules.caseTitle, required: false },
    description: { ...CommonValidationRules.caseDescription, required: false },
    categoryId: { ...CommonValidationRules.id, required: false },
    industry: {
      type: 'string' as const,
      required: false,
      maxLength: 50,
      message: '行业不能超过50字符'
    },
    client: {
      type: 'string' as const,
      required: false,
      maxLength: 100,
      message: '客户名称不能超过100字符'
    },
    projectDate: {
      type: 'string' as const,
      required: false,
      pattern: /^\d{4}-\d{2}-\d{2}$/,
      message: '项目日期格式应为YYYY-MM-DD'
    },
    images: {
      type: 'array' as const,
      required: false
    },
    services: {
      type: 'array' as const,
      required: false
    },
    tags: {
      type: 'array' as const,
      required: false
    },
    status: { ...CommonValidationRules.status, required: false },
    sort: { ...CommonValidationRules.sort, required: false }
  }),

  // 联系人相关验证
  validateContactCreate: createValidationMiddleware({
    name: CommonValidationRules.contactName,
    position: { ...CommonValidationRules.contactPosition, required: false },
    phone: { ...CommonValidationRules.phone, required: true },
    wechat: {
      type: 'string' as const,
      required: false,
      maxLength: 50,
      message: '微信号不能超过50字符'
    },
    email: { ...CommonValidationRules.email, required: false },
    description: {
      type: 'string' as const,
      required: false,
      maxLength: 500,
      message: '描述不能超过500字符'
    },
    specialties: {
      type: 'string' as const,
      required: false,
      maxLength: 200,
      message: '专长不能超过200字符'
    },
    workingHours: {
      type: 'string' as const,
      required: false,
      maxLength: 100,
      message: '工作时间不能超过100字符'
    },
    languages: {
      type: 'string' as const,
      required: false,
      maxLength: 100,
      message: '语言能力不能超过100字符'
    },
    isPublic: {
      type: 'boolean' as const,
      required: false
    },
    isActive: {
      type: 'boolean' as const,
      required: false
    },
    sort: { ...CommonValidationRules.sort, required: false }
  }),

  validateContactUpdate: createValidationMiddleware({
    name: { ...CommonValidationRules.contactName, required: false },
    position: { ...CommonValidationRules.contactPosition, required: false },
    phone: { ...CommonValidationRules.phone, required: false },
    wechat: {
      type: 'string' as const,
      required: false,
      maxLength: 50,
      message: '微信号不能超过50字符'
    },
    email: { ...CommonValidationRules.email, required: false },
    description: {
      type: 'string' as const,
      required: false,
      maxLength: 500,
      message: '描述不能超过500字符'
    },
    specialties: {
      type: 'string' as const,
      required: false,
      maxLength: 200,
      message: '专长不能超过200字符'
    },
    workingHours: {
      type: 'string' as const,
      required: false,
      maxLength: 100,
      message: '工作时间不能超过100字符'
    },
    languages: {
      type: 'string' as const,
      required: false,
      maxLength: 100,
      message: '语言能力不能超过100字符'
    },
    isPublic: {
      type: 'boolean' as const,
      required: false
    },
    isActive: {
      type: 'boolean' as const,
      required: false
    },
    sort: { ...CommonValidationRules.sort, required: false }
  }),

  // 通用验证
  validateId: validateParams({
    id: CommonValidationRules.id
  }),

  validatePagination: validateQuery({
    page: {
      type: 'number' as const,
      required: false,
      min: 1,
      message: '页码必须大于0'
    },
    pageSize: {
      type: 'number' as const,
      required: false,
      min: 1,
      max: 100,
      message: '每页数量必须在1-100之间'
    },
    keyword: {
      type: 'string' as const,
      required: false,
      maxLength: 100,
      message: '搜索关键词不能超过100字符'
    },
    status: { ...CommonValidationRules.status, required: false },
    sort: {
      type: 'string' as const,
      required: false,
      custom: (value: string) => ['asc', 'desc', 'createdAt', 'updatedAt', 'sort'].includes(value),
      message: '排序字段必须是asc、desc、createdAt、updatedAt或sort'
    }
  }),

  validateSortUpdate: createValidationMiddleware({
    items: {
      type: 'array' as const,
      required: true,
      custom: (value: any[]) => {
        if (!Array.isArray(value)) return false;
        return value.every(item => 
          typeof item === 'object' && 
          typeof item.id === 'string' && 
          typeof item.sort === 'number'
        );
      },
      message: '排序数据格式不正确'
    }
  })
};

/**
 * 文件上传验证
 */
export function validateFileUpload(options: {
  maxSize?: number; // 最大文件大小（字节）
  allowedTypes?: string[]; // 允许的文件类型
  required?: boolean;
}) {
  return ({ body, set }: Context) => {
    const { maxSize = 5 * 1024 * 1024, allowedTypes = [], required = false } = options;
    
    if (!body || !body.file) {
      if (required) {
        set.status = 400;
        throw ApiError.validation('文件不能为空');
      }
      return;
    }

    const file = body.file;
    
    // 检查文件大小
    if (file.size > maxSize) {
      set.status = 400;
      throw ApiError.validation(`文件大小不能超过${Math.round(maxSize / 1024 / 1024)}MB`);
    }

    // 检查文件类型
    if (allowedTypes.length > 0 && !allowedTypes.includes(file.type)) {
      set.status = 400;
      throw ApiError.validation(`文件类型必须是${allowedTypes.join('、')}`);
    }
  };
}

/**
 * 批量操作验证
 */
export function validateBatchOperation(maxItems: number = 100) {
  return createValidationMiddleware({
    ids: {
      type: 'array' as const,
      required: true,
      maxLength: maxItems,
      custom: (value: any[]) => {
        if (!Array.isArray(value)) return false;
        return value.every(id => typeof id === 'string' && id.length > 0);
      },
      message: `批量操作最多支持${maxItems}个项目，且ID不能为空`
    }
  });
}